package com.hxzy.config;

import com.hxzy.config.interceptor.AdminTokenInterceptor;
import com.hxzy.config.interceptor.MobileTokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * @Desc springmvc的核心配置文件
 * @Author: admin
 * @Date: 2023/06/29/17:12
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 自定义令牌有效性拦截器
     */
    @Autowired
    private AdminTokenInterceptor adminTokenInterceptor;

    /**
     * 手机端令牌有效性拦截器
     */
    @Autowired
    private MobileTokenInterceptor  mobileTokenInterceptor;

    /**
     * 添加自定义拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //放行的url 后台的
        List<String> excludeUrls=new ArrayList<>();
        excludeUrls.add("/api/login");
        excludeUrls.add("/api/captcha");
        //添加令牌拦截器
        registry.addInterceptor(adminTokenInterceptor).addPathPatterns("/api/**").excludePathPatterns(excludeUrls);


        //放行的url手机端
        List<String> excludeMobileUrls=new ArrayList<>();
        excludeMobileUrls.add("/mobile/login");

        //添加令牌拦截器
        registry.addInterceptor(mobileTokenInterceptor).addPathPatterns("/mobile/**").excludePathPatterns(excludeMobileUrls);

    }


    /**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilter()
    {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置访问源地址
        config.addAllowedOriginPattern("*");
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 有效期 1800秒
        config.setMaxAge(1800L);

        // 添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }


}
